package com.emapp.lccode.utils;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Author:YanshanZhang
 * E-mail:690810892@qq.com
 * Date: 2022/5/16 11:14
 * Desc:
 */
public class NativeLibraryLoader {
    public static boolean loadLibrary(Context context, String oldFileName, String libName) throws IOException {
        // 获取应用的私有模式的libs目录（真实的目录是app-libs）
        File libs_dir = context.getDir("libs", Context.MODE_PRIVATE);
        // 可以获取到assets资源文件的数据流
        InputStream open = context.getAssets().open(oldFileName);
        String new_file_name = libs_dir.getPath() + "/" + libName;
        // 把资源文件的数据流写入到app-libs目录下
        if (!copyLibrary(open, new_file_name)) {
            return false;
        }
        try {
            System.load(new_file_name);
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }

        return true;
    }
    //从assets资源目录下复制到app-libs目录下
    public static boolean copyLibrary(InputStream fileInputStream, String new_file) {

        FileOutputStream fos = null;
        try {

            File file = new File(new_file);
            fos = new FileOutputStream(file);
            int     dataSize;
            byte[]  dataBuffer = new byte[2048];

            while ((dataSize = fileInputStream.read(dataBuffer)) != -1) {
                fos.write(dataBuffer, 0, dataSize);
            }
            fos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("NativeLibraryLoader",e.getMessage());
        } finally {
            try {
                if (fos != null) fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return false;
    }

}
